<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\library\Sms as Smslib;
use app\common\model\Attachment;
use fast\OpenWx;
use think\Config;
use think\Cookie;
use think\Db;
use think\Hook;
use think\Session;
use think\Validate;
use function fast\e;

/**
 * 会员中心
 */
class Users extends Frontend
{
    protected $layout = 'default';
    protected $noNeedLogin = ['login', 'register', 'third','opWxLogin','forget'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'), '/');
        }

        //监听注册登录退出的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        Hook::add('user_register_successed', function ($user) use ($auth) {
            Cookie::set('uid', $user->id);
            Cookie::set('token', $auth->getToken());
        });
        Hook::add('user_delete_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
        Hook::add('user_logout_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
        $this->view->assign('msgcount', 0);


    }

    /**
     * 会员中心
     */
    public function index()
    {

        $this->view->assign('title', __('User center'));
        $this->view->assign('act', 'index');
        return $this->view->fetch();
    }
    public function mylt()
    {
        $this->view->assign('title', __('我的论坛'));
        $this->view->assign('act', 'mylt');

        return $this->view->fetch();
    }
    public function msg()
    {

        $user = $this->auth->getUser();

//        $list = Db::name('lyb')
//            ->where('user_id',$user['id'])
//           ->paginate(10, false, ['query' => request()->param()]);
//

        $list = Db::name('lyb')
            ->where('user_id',$user['id'])
            ->order('id','desc')
            ->select();
        $pp = [];
        $msgcount = 0;
        foreach ($list as $k=>$v){
            $hf = Db::name('lyb')
                ->where('pid',$v['id'])
                ->order('id','asc')
                ->select();

            array_push($pp,$v);
            foreach ($hf as $k1=>$v1){
                if($v1['yddata']==0){
                    $msgcount++;
                }
                Db::name('lyb')
                    ->where('id',$v1['id'])
                    ->update([
                        'yddata'=>1,
                        'updatetime'=>time()
                    ]);
                array_push($pp,$v1);

            }
        }




        $this->view->assign('list', $pp);
        $this->view->assign('title', __('我的消息'));
        $this->view->assign('act', 'msg');

        $this->view->assign('msgcount', $msgcount);

        return $this->view->fetch();
    }
    public function addMsg()
    {
        $content = input('content');
        $user = $this->auth->getUser();


        if(empty($content)){
            $this->error('请输入留言信息');
        }

        $info = Db::name('lyb')
            ->where('user_id',$user['id'])
            ->where('content',$content)
            ->find();
        if(!empty($info)){
            $this->error('请勿提交重复信息');
        }
        Db::name('lyb')
            ->insert([
                'user_id'=>$user['id'],
                'content'=>$content,
                'createtime'=>time(),
                'updatetime'=>time(),
            ]);
        $this->success('提交成功',url('users/msg'));
    }
    public function delMsg()
    {
        $id = input('id');
        $user = $this->auth->getUser();

        $info = Db::name('lyb')
            //->where('user_id',$user['id'])
            ->where('id',$id)
            ->find();
        if(empty($info)){
            $this->error('信息不存在');
        }
        $hf = Db::name('lyb')
            ->where('pid',$info['id'])
            ->order('id','asc')
            ->select();
        $ids = [];
        array_push($ids,$info['id']);
        foreach ($hf as $k=>$v){
            array_push($ids,$v['id']);
        }
        Db::name('lyb')
            ->where('id','in',$ids)
            ->delete();
        $this->success('删除成功',url('users/msg'));
    }
    public function comment()
    {
        $this->view->assign('title', __('我的评论'));
        $this->view->assign('act', 'comment');

        return $this->view->fetch();
    }
    public function flow()
    {
        $this->view->assign('title', __('我的关注'));
        $this->view->assign('act', 'flow');

        return $this->view->fetch();
    }
    public function kecheng()
    {
        $this->view->assign('title', __('我的课程'));
        $this->view->assign('act', 'kecheng');

        return $this->view->fetch();
    }
    /**
     * 注册会员
     */
    public function register()
    {
        $url = $this->request->request('url', '', 'url_clean');
        if ($this->auth->id) {
            $this->success(__('You\'ve logged in, do not login again'), $url ? $url : url('user/index'));
        }
        if ($this->request->isPost()) {
            $username = $this->request->post('username');
            $password = $this->request->post('password', '', null);
            $confirm_password = $this->request->post('confirm_password', '', null);
            $mobile = $this->request->post('mobile', '');
            $code = $this->request->post('code');
            $token = $this->request->post('__token__');
            $keeplogin = (int)$this->request->post('keeplogin');

            if(empty($keeplogin)){
                $this->error('请勾选用户协议和隐私政策');

            }
            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:6,30',
                'mobile'    => 'regex:/^1\d{10}$/',
                'code'    => 'require',
               // '__token__' => 'require|token',
            ];

            $msg = [
                'username.require' => 'Username can not be empty',
                'username.length'  => 'Username must be 3 to 30 characters',
                'password.require' => 'Password can not be empty',
                'password.length'  => 'Password must be 6 to 30 characters',
                'mobile'           => 'Mobile is incorrect',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
                'mobile'    => $mobile,
                'code'    => $code,
                //'__token__' => $token,
            ];
            if($password!=$confirm_password){
                $this->error('两次密码不一致');
            }
                //验证码
            $captchaResult = Sms::check($mobile, $code, 'register');

            if (!$captchaResult) {
                $this->error(__('Captcha is incorrect'));
            }
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }
            if ($this->auth->register($username, $password, '', $mobile)) {
                $this->success(__('Sign up successful'), $url ? $url : url('user/index'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER', '', 'url_clean');
        if (!$url && $referer && !preg_match("/(user\/login|user\/register|user\/logout)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('captchaType', config('fastadmin.user_register_captcha'));
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Register'));
        return $this->view->fetch();
    }


    public function loginBySms(){
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');

        $userinfo = \app\common\model\User::getByMobile($mobile);
        if(empty($userinfo)){
            $this->error(__('未注册'));
        }
        $ret = Sms::check($mobile, $code, 'login');
        if(!$ret){
            $this->error('验证码错误');
        }
        $r = $this->auth->direct($userinfo['id']);
        if($r){
            $this->success('登录成功');
        }
        $this->error('登录失败');


    }


    /**
     * 会员登录
     */
    public function login()
    {
        $url = $this->request->request('url', '', 'url_clean');
        if ($this->auth->id) {
            $this->success(__('You\'ve logged in, do not login again'), $url ?: url('user/index'));
        }
        if ($this->request->isPost()) {
            $account = $this->request->post('account');
            $password = $this->request->post('password', '', null);
            $keeplogin = (int)$this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $loginType = $this->request->post('loginType', 0);
            $code = $this->request->post('code', '');
            if(empty($keeplogin)){
                $this->error('请勾选用户协议和隐私政策');

            }
            $rule = [
                'account'   => 'require|length:3,50',
               // 'password'  => 'require|length:6,30',
               // '__token__' => 'require|token',
            ];

            $msg = [
                'account.require'  => 'Account can not be empty',
                'account.length'   => 'Account must be 3 to 50 characters',
               // 'password.require' => 'Password can not be empty',
               // 'password.length'  => 'Password must be 6 to 30 characters',
            ];
            $data = [
                'account'   => $account,
               // 'password'  => $password,
               // '__token__' => $token,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }
            if($loginType==0){
                if(empty($password)){
                    $this->error('密码不能为空');
                }
                if ($this->auth->login($account, $password)) {
                    $this->success(__('Logged in successful'), $url ? $url : url('user/index'));
                } else {
                    $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
                }
            }else{
                if(empty($code)){
                    $this->error('验证码不能为空');
                }
                if ($this->auth->loginBySms($account, $code)) {
                    $this->success(__('Logged in successful'), $url ? $url : url('user/index'));
                } else {
                    $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
                }
            }




        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER', '', 'url_clean');
        if (!$url && $referer && !preg_match("/(user\/login|user\/register|user\/logout)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('url', $url);
        $this->view->assign('redirect_uri',http().'/opWxLogin' );
        $this->view->assign('title', __('Login'));
        return $this->view->fetch();
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        if ($this->request->isPost()) {
            //$this->token();
            //退出本站
            $this->auth->logout();
            $this->success(__('退出成功'), url('index/index'));
        }
        $html = "<form id='logout_submit' name='logout_submit' action='' method='post'>" . token() . "<input type='submit' value='ok' style='display:none;'></form>";
        $html .= "<script>document.forms['logout_submit'].submit();</script>";

        return $html;
    }

    /**
     * 个人信息
     */
    public function profile()
    {
        $this->view->assign('title', __('Profile'));
        return $this->view->fetch();
    }

    /**
     * 修改密码
     */
    public function changepwd()
    {
        if ($this->request->isPost()) {
            $mobile = $this->request->post("mobile", '', null);
            $code = $this->request->post("code", '', null);
            $oldpassword = $this->request->post("oldpassword", '', null);
            $newpassword = $this->request->post("newpassword", '', null);
            $renewpassword = $this->request->post("renewpassword", '', null);
            $token = $this->request->post('__token__');
            $rule = [
                'mobile'   => 'require',
                'code'   => 'require',
                'oldpassword'   => 'require|regex:\S{6,30}',
                'newpassword'   => 'require|regex:\S{6,30}',
                'renewpassword' => 'require|regex:\S{6,30}|confirm:newpassword',
               // '__token__'     => 'token',
            ];

            $msg = [
                'renewpassword.confirm' => __('Password and confirm password don\'t match')
            ];
            $data = [
                'mobile'   => $mobile,
                'code'   => $code,
                'oldpassword'   => $oldpassword,
                'newpassword'   => $newpassword,
                'renewpassword' => $renewpassword,
                //'__token__'     => $token,
            ];
            $field = [
                'mobile'   => __('手机号'),
                'code'   => __('验证码'),
                'oldpassword'   => __('Old password'),
                'newpassword'   => __('New password'),
                'renewpassword' => __('Renew password')
            ];
            $validate = new Validate($rule, $msg, $field);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }
            $captchaResult = Sms::check($mobile, $code, 'changepwd');

            $ret = $this->auth->changepwd($newpassword, $oldpassword);
            if ($ret) {
                $this->success(__('Reset password successful'), url('user/login'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        $this->view->assign('title', __('Change password'));
        return $this->view->fetch();
    }

    public function attachment()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $mimetypeQuery = [];
            $where = [];
            $filter = $this->request->request('filter');
            $filterArr = (array)json_decode($filter, true);
            if (isset($filterArr['mimetype']) && preg_match("/(\/|\,|\*)/", $filterArr['mimetype'])) {
                $this->request->get(['filter' => json_encode(array_diff_key($filterArr, ['mimetype' => '']))]);
                $mimetypeQuery = function ($query) use ($filterArr) {
                    $mimetypeArr = array_filter(explode(',', $filterArr['mimetype']));
                    foreach ($mimetypeArr as $index => $item) {
                        $query->whereOr('mimetype', 'like', '%' . str_replace("/*", "/", $item) . '%');
                    }
                };
            } elseif (isset($filterArr['mimetype'])) {
                $where['mimetype'] = ['like', '%' . $filterArr['mimetype'] . '%'];
            }

            if (isset($filterArr['filename'])) {
                $where['filename'] = ['like', '%' . $filterArr['filename'] . '%'];
            }

            if (isset($filterArr['createtime'])) {
                $timeArr = explode(' - ', $filterArr['createtime']);
                $where['createtime'] = ['between', [strtotime($timeArr[0]), strtotime($timeArr[1])]];
            }
            $search = $this->request->get('search');
            if ($search) {
                $where['filename'] = ['like', '%' . $search . '%'];
            }

            $model = new Attachment();
            $offset = $this->request->get("offset", 0);
            $limit = $this->request->get("limit", 0);
            $total = $model
                ->where($where)
                ->where($mimetypeQuery)
                ->where('user_id', $this->auth->id)
                ->order("id", "DESC")
                ->count();

            $list = $model
                ->where($where)
                ->where($mimetypeQuery)
                ->where('user_id', $this->auth->id)
                ->order("id", "DESC")
                ->limit($offset, $limit)
                ->select();
            $cdnurl = preg_replace("/\/(\w+)\.php$/i", '', $this->request->root());
            foreach ($list as $k => &$v) {
                $v['fullurl'] = ($v['storage'] == 'local' ? $cdnurl : $this->view->config['upload']['cdnurl']) . $v['url'];
            }
            unset($v);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $mimetype = $this->request->get('mimetype', '');
        $mimetype = substr($mimetype, -1) === '/' ? $mimetype . '*' : $mimetype;
        $this->view->assign('mimetype', $mimetype);
        $this->view->assign("mimetypeList", \app\common\model\Attachment::getMimetypeList());
        return $this->view->fetch();
    }

    public function opWxLogin(){
        $code= input('code','');
        if(empty($code)){
            $this->error('code错误');
        }
        $obj = new OpenWx(config('open_appid'),config('open_secret'));
        $res = $obj->oauth2_access_token($code);
        if(!empty($res)){
            $user = $obj->oauth2_get_user_info($res['access_token'],$res['openid']);
            if(!empty($user)){

                $a = [
                    'nickname'=>$user['openid'],
                    'username'=>$user['nickname'],
                    'openid'=>$user['openid'],
                    'avatar'=>$user['headimgurl'],
                    'updatetime'=>time(),
                ];
                $check = Db::name('user')
                    ->where('openid',$user['openid'])
                    ->find();
                if(empty($check)){
                    $a['createtime'] = time();
                    $uid = Db::name('user')
                        ->insertGetId($a);
                }else{
                    $r = Db::name('user')
                        ->where('id',$check['id'])
                        ->update($a);
                    $uid = $check['id'];
                }

               $r =  $this->auth->direct($uid);
               if($r){
                   $this->success('登录成功');
               }
               $this->error('登录失败');
            }else{
                $this->error(json_encode($res));
            }
        }else{
            $this->error(json_encode($res));

        }
    }

    public function forget(){
        $url = $this->request->request('url', '', 'url_clean');
        if ($this->auth->id) {
            $this->success(__('You\'ve logged in, do not login again'), $url ?: url('user/index'));
        }
        if ($this->request->isPost()) {
            $mobile = $this->request->post("mobile");
            $newpassword = $this->request->post("newpassword");
            $confirm_password = $this->request->post("confirm_password");
            $captcha = $this->request->post("captcha");
            if (!$newpassword || !$captcha) {
                $this->error(__('Invalid parameters'));
            }
            //验证Token
            if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
                $this->error(__('Password must be 6 to 30 characters'));
            }

            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            if($newpassword!=$confirm_password){
                $this->error(__('两次密码不一致'));

            }
            Sms::flush($mobile, 'resetpwd');
            //模拟一次登录
            $this->auth->direct($user->id);
            $ret = $this->auth->changepwd($newpassword, '', true);
            if ($ret) {
                $this->success(__('Reset password successful'),url('user/login'));
            } else {
                $this->error($this->auth->getError());
            }

        }

        $this->view->assign('title', __('忘记密码'));
        return $this->view->fetch();
    }
}
